/*
Given a collection of integers that might contain duplicates, S, return all possible subsets.

Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If S = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]
*/

class Solution {
public:
    vector<vector<int> > subsetsWithDup(vector<int> &S) {
        vector<vector<int> >res;
        vector<int> resone;
        sort(S.begin(), S.end());
        subsetWithDup(resone, res, S, 0);
        return res;
    }
private:
    void subsetWithDup(vector<int> &resone, vector<vector<int> > &res, vector<int> &numbers, int start) {
        res.push_back(resone);
        for (int i = start; i < numbers.size(); i++) {
            if (i>start && numbers[i] == numbers[i-1]) continue;
            resone.push_back(numbers[i]);
            // continue with next number
            subsetWithDup(resone, res, numbers, i+1);
            resone.pop_back();
        }
    }
};
